<template>
  <Pannel>
    <Navbar>
      <template #right>
        <Filter v-if="active != 0" @reset="handleReset" @submit="handleSubmit">
          <DPicker
            v-model="filterFormData.overState"
            is-link
            readonly
            label="是否结单"
            placeholder="请选择"
            :required="true"
            :list="STATEMENT_ACCOUNT"
          />
          <DPicker
            v-model="filterFormData.overtimeState"
            is-link
            readonly
            label="是否超时"
            placeholder="请选择"
            :required="true"
            :list="IS_TIMEOUT"
          />
          <DPicker
            v-model="filterFormData.unit"
            is-link
            readonly
            label="单元区域"
            placeholder="请选择"
            :required="true"
            :list="store[dictNames.UNIT]"
          />
          <DPicker
            v-model="filterFormData.customerTag"
            is-link
            readonly
            label="客户标识"
            placeholder="请选择"
            :required="true"
            :list="store[dictNames.CUSTOMER_TAG]"
          />
          <DPicker
            v-model="filterFormData.customerDemand"
            is-link
            readonly
            label="客户需求"
            placeholder="请选择"
            :required="true"
            :list="store[dictNames.CUSTOMER_DEMAND]"
          />
          <DTimePicker
            v-model="filterFormData.preparedTimeStart"
            is-link
            readonly
            label="开始时间"
            placeholder="请选择"
            :required="true"
            :list="columns"
          />
          <DTimePicker
            v-model="filterFormData.preparedTimeEnd"
            is-link
            readonly
            label="结束时间"
            placeholder="请选择"
            :required="true"
            :list="columns"
          />
        </Filter>
      </template>
    </Navbar>

    <van-tabs
      ref="oTabsRef"
      v-model:active="active"
      class="custom-scroll-tabs"
      :ellipsis="false"
      sticky
    >
      <van-tab v-for="(tab, index) of tabList" :title="tab.title" :key="index">
        <template #title>
          <div class="define-tab-title">
            <span class="title">{{ tab.title }}</span>
            <span class="point" v-show="newData[tab.type] > 0"></span>
          </div>
        </template>
      </van-tab>
    </van-tabs>

    <!-- 动态组件放在 tabs 外面，避免生命周期叠加问题 -->
    <div class="tab-body">
      <Suspense>
        <!-- 已加载/缓存的组件 -->
        <KeepAlive :include="cachedNames">
          <component
            ref="oCurrentComponent"
            :is="currentComponent"
            :key="active"
          />
        </KeepAlive>

        <!-- 骨架屏 -->
        <template #fallback>
          <van-skeleton title :row="3" />
        </template>
      </Suspense>
    </div>
  </Pannel>
</template>

<script setup>
import { NEW_DATA } from "@/config/dict.js";
import { hasNewData } from "@/api/index.js";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { defineAsyncComponent } from "vue";
import {
  showLoadingToast,
  closeToast,
  showSuccessToast,
} from "@/utils/toast.js";

//  监听路由
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

const tabList = [
  { title: "创建工单", type: "", name: "CompCreate" },
  { title: "我的工单", type: "", name: "CompMy" },
  {
    title: "待我转派",
    type: NEW_DATA.WAIT_TRANSFER,
    name: "CompWaitTransfer",
  },
  { title: "待我处理", type: NEW_DATA.WAIT_HANDLE, name: "CompWaitHandle" },
  {
    title: "待我结单",
    type: NEW_DATA.WAIT_COMPELETE,
    name: "CompWaitComplete",
  },
];

/* 1. 用 defineAsyncComponent 异步加载 */
const components = {
  CompCreate: defineAsyncComponent(() => import("./components/create.vue")),
  CompMy: defineAsyncComponent(() => import("./components/my.vue")),
  CompWaitTransfer: defineAsyncComponent(() =>
    import("./components/wait_transfer.vue")
  ),
  CompWaitHandle: defineAsyncComponent(() =>
    import("./components/wait_handle.vue")
  ),
  CompWaitComplete: defineAsyncComponent(() =>
    import("./components/wait_complete.vue")
  ),
};

import useTabIndex from "@/store/tabIndex.js";
const [active, setActive] = useTabIndex();

// 监听 store 中的 active 变化
watch(active, async (newVal) => {
  setActive(newVal);
  newData.value = (await hasNewData())?.resc || {};
});

/* 2. 当前要渲染的组件 */
const currentComponent = computed(() => {
  const name = tabList[active.value].name;

  return components[name];
});

/* 3. 告诉 KeepAlive 缓存哪些组件（可选） */
const cachedNames = computed(() => tabList.map((i) => i.name));

//  接收页面是否有更新
const newData = ref({});
//  tab 实例
const oTabsRef = ref(null);

console.log("newData");

onMounted(async () => {
  console.log("newData");
  newData.value = (await hasNewData())?.resc || {};
  nextTick(() => oTabsRef.value?.resize());
});

const oCurrentComponent = ref(null);

//  筛选
const filterFormData = reactive({
  overState: "", //是否结单
  overtimeState: "", //是否超时
  unit: "", //单元
  customerTag: "", //客户标识
  customerDemand: "", //客户需求
  preparedTimeStart: "", //录入时间开始日期
  preparedTimeEnd: "", //录入时间结束日期
});

//  重置 filterFormData
const handleReset = () => {
  Object.keys(filterFormData).forEach((key) => {
    filterFormData[key] = "";
  });
};

//  提交 filterFormData
const handleSubmit = async () => {
  if (oCurrentComponent.value) {
    await oCurrentComponent.value.fetchData(filterFormData);
    handleReset();
  }
};

//  加载字典项
import {
  STATEMENT_ACCOUNT,
  CUSTOMER_COMMENT,
  IS_TIMEOUT,
} from "@/config/dict.js";

import useDict from "@/store/dict.js";
import dictNames from "@/config/dict.js";

const [store, setDict] = useDict();

//  jia
onMounted(async () => {
  console.log("fetchDatas");
  showLoadingToast();
  await fetchDatas();
  closeToast();
});

function fetchDatas() {
  setDict([dictNames.UNIT, dictNames.CUSTOMER_TAG, dictNames.CUSTOMER_DEMAND]);
}
</script>

<style lang="scss" scoped>
/* 让 tab 可以横向滑动 */
.custom-scroll-tabs ::v-deep(.van-tabs__wrap) {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch; /* 移动端顺滑滚动 */
}

.custom-scroll-tabs ::v-deep(.van-tabs__nav) {
  flex-wrap: nowrap;
  min-width: 100%;
}

/* 隐藏滚动条（可选） */
.custom-scroll-tabs ::v-deep(.van-tabs__wrap::-webkit-scrollbar) {
  display: none;
}

.custom-scroll-tabs .define-tab-title {
  display: flex;
  width: 100%;
  box-sizing: border-box;

  .point {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: red;
    margin-left: 4px;
  }
}

.tab-body {
  margin-top: 16px;
}
</style>